﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MS.InformationManagement.Core.Support;
using MS.InformationManagement.DAL.DTOs;
using Microsoft.SharePoint;
using office = Microsoft.Office.DocumentManagement.DocumentSets;
using MS.InformationManagement.Support;
using MS.InformationManagement.Support.Constants;
using MS.InformationManagement.Support.Enums;
using MS.InformationManagement.DAL.DocumentCenter;

namespace MS.InformationManagement.BLL.ShippingControlTemplates
{
    public class MarkRadicadoAsReturnedCommand : IBaseCommand
    {
        #region Fields

        IEnumerable<PlanillasDTO> _foundItems;
        List<office.DocumentSet> _documentsBackup = new List<office.DocumentSet>();
        string _currentUser;

        #endregion

        #region Constructors

        public MarkRadicadoAsReturnedCommand(IEnumerable<PlanillasDTO> foundItems)
        {
            _foundItems = foundItems;
        }

        #endregion

        #region Implemented Methods

        public void Execute()
        {
            _currentUser = SPContext.Current.Web.CurrentUser.LoginName;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite currentSite = new SPSite(SPContext.Current.Site.ID))
                {
                    using (SPWeb currentWeb = currentSite.OpenWeb())
                    {
                        currentWeb.AllowUnsafeUpdates = true;
                        currentSite.AllowUnsafeUpdates = true;

                        foreach (var entity in _foundItems)
                        {
                            SPList documentsList = currentWeb.Lists[entity.IdList];
                            SPListItem documentListItem = documentsList.GetItemById(entity.IdItem);
                            SPFolder currentDocItem = documentListItem.Folder != null ? documentListItem.Folder : documentListItem.File.ParentFolder;
                            office.DocumentSet currentDocument = office.DocumentSet.GetDocumentSet(currentDocItem);
                            _documentsBackup.Add(currentDocument);

                            //Update Fields

                            currentDocument.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_STATUS_SENT] = false;
                            currentDocument.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_STATUS_DELIVERED] = false;
                            currentDocument.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_STATUS_RETURNED] = true;

                            if (!entity.Reprogrmar )
                            {
                                currentDocument.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_STATUS_PRINTED] = entity.Recibido;
                                currentDocument.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_STATUS_WINDOW] = entity.Recibido;
                                currentDocument.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_STATUS_WEIGHT] = entity.Recibido;
                                currentDocument.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_STATUS_CAPTURED] = entity.Recibido;
                            }

                            //Update Logs
                            string documentDepartment = PeopleHelper.GetPropertyUserProfile(GlobalConstants.UP_DEPARTMENT, currentDocument.Folder.Item[CustomSiteColumns.FIELD_EXPEDIENTE_ASSIGNED].ToString());
                            DeliveryTraceabilityEntry deliveryLogEntry = this.getDeliverEntity(entity, documentDepartment);
                            currentDocument.UpdateDeliveryLog(deliveryLogEntry);
                            currentDocument.Log(string.Empty, DateTime.Now, TraceableOperation.Devuelto, _currentUser, string.Empty);


                            currentDocument.Folder.Item.Update();
                            currentDocument.Folder.Update();

                            SendEmail(entity.UsuarioAsignado, entity.NoRadicado, entity.Destinatario);
                        }

                        currentSite.AllowUnsafeUpdates = false;
                        currentWeb.AllowUnsafeUpdates = false;
                    }
                }
            });
        }

        public void Undo()
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite currentSite = new SPSite(SPContext.Current.Site.ID))
                {
                    using (SPWeb currentWeb = currentSite.OpenWeb())
                    {
                        foreach (office.DocumentSet entity in _documentsBackup)
                        {
                            office.DocumentSet currentDocument = office.DocumentSet.GetDocumentSet(entity.Folder);

                            currentDocument.ParentList.ParentWeb.AllowUnsafeUpdates = true;
                            currentDocument.ParentList.ParentWeb.Site.AllowUnsafeUpdates = true;

                            currentDocument.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_STATUS_SENT] = entity.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_STATUS_SENT];
                            currentDocument.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_STATUS_DELIVERED] = entity.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_STATUS_DELIVERED];
                            currentDocument.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_STATUS_RETURNED] = entity.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_STATUS_RETURNED];
                            currentDocument.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_STATUS_PRINTED] = entity.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_STATUS_PRINTED];
                            currentDocument.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_STATUS_WINDOW] = entity.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_STATUS_WINDOW];
                            currentDocument.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_STATUS_WEIGHT] = entity.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_STATUS_WEIGHT];
                            currentDocument.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_STATUS_CAPTURED] = entity.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_STATUS_CAPTURED];

                            ///Eliminar Logs

                            currentDocument.Folder.Item.Update();
                            currentDocument.Folder.Update();

                            currentDocument.ParentList.ParentWeb.AllowUnsafeUpdates = false;
                            currentDocument.ParentList.ParentWeb.Site.AllowUnsafeUpdates = false;

                        }
                    }
                }
            });
        }

        #endregion


        #region Private Methods

        private DeliveryTraceabilityEntry getDeliverEntity(PlanillasDTO currentEntity, string department)
        {
            DeliveryTraceabilityEntry logEntry = new DeliveryTraceabilityEntry();
            logEntry.Address = currentEntity.Direccion;
            logEntry.Area = department;
            logEntry.City = currentEntity.Ciudad;
            logEntry.DateTime = DateTime.Now;
            logEntry.To = currentEntity.Destinatario;
            logEntry.Operation = DeliveryOperations.Devuelto.ToString();
            logEntry.User = _currentUser;
            return logEntry;
        }


        private static void SendEmail(string UserLogin, string NumeroRadicado, string Destinatario)
        {
            string toField = new MS.InformationManagement.BLL.GestionDeUsuarios.GestionDeUsuariosBLL().getProperty(GlobalConstants.UP_EMAIL, UserLogin);
            string subject = "Correspondencia";
            string body = string.Format("El radicado de salida {0} dirigido a {1} NO ha sido entregado exitosamente. Favor dirigase al modulo de 'Devoluciones' para conocer detalles.", NumeroRadicado, Destinatario);
            EmailHelper.SendEmail(toField, subject, body);
        }

        #endregion
    }
}
